/**
 * 按帧读取两个pcm文件，并进行混音，输出为一个帧
 *
 */
const beamcoder = require('beamcoder');
const {writeData, readFileAsFrames} = require("../../util/util");

async function getMuxFilter(){
	let a_filterer = await beamcoder.filterer({
		filterType: 'audio',
		inputParams: [
			{
				name:'a1',
				sampleRate: 16000,
				sampleFormat: 's16',
				channelLayout: 'stereo',
				timeBase: [1,16000]
			},
			{
				name:'a2',
				sampleRate: 16000,
				sampleFormat: 's16',
				channelLayout: 'stereo',
				timeBase: [1,16000]
			}
		],
		outputParams: [
			{
				sampleRate: 16000,
				sampleFormat: 's16',
				channelLayout: 'stereo',
				timeBase: [1,16000]
			}
		],
		filterSpec: '[a1][a2]amix=inputs=2:duration=longest'
		// filterSpec: '[a1][a2]amerge=inputs=2'
	});

	return a_filterer;
}

function buildFrame(frameData){
	let pkt_size = frameData.byteLength;
	let pkt_duration = pkt_size / 4;

	let fr2 = beamcoder.frame({
		type: 'Frame',
		lineSize: [frameData.byteLength],
		format: 's16',
		key_frame: true,
		sample_rate: 16000,
		channel_layout: 'stereo',
		channels: 2,
		nb_samples:pkt_duration,
		sample_aspect_ratio:[0,1],
		// pkt_size,
		// pkt_duration,
		// pts,
		// pkt_dts,
		data:[frameData]
	});
	return fr2;
}

async function mixer(bgArray, fgArray){
	let finalLen = bgArray.length > fgArray.length? fgArray.length: bgArray.length;

	let finalArray = []
	let muxFilter = await getMuxFilter();

	for(let i=0;i<finalLen;i++){
		let frame1 = buildFrame(bgArray[i]);
		let frame2 = buildFrame(fgArray[i]);
		let data = await muxFilter.filter([{name:'a1', frames:[frame1]},{name:'a2', frames:[frame2]}]);
		console.log('output data length:', data[0].frames[0].data[0].byteLength);
		let realAudioData = data[0].frames[0].data[0];
		//需要去掉buffer最后为了对齐增加的空白数据
		realAudioData = realAudioData.slice(0, 1280);
		finalArray.push(realAudioData);
	}
	return finalArray;
}

async function main(){
    let bg_music="../media/28s_bg_music.pcm";
    let fg_sound = "../media/long_human_sound.pcm";
    let bgArray = await readFileAsFrames(bg_music);
    let fgArray  = await readFileAsFrames(fg_sound);
    console.log(`read media file over, bg:${bgArray.length}, fg:${fgArray.length}`);

	let totalArray = await mixer(bgArray, fgArray);
	await writeData(totalArray, 'finalData.pcm');
	console.log(`total Result:${totalArray.length}`);
}

main();